/*
*  LLFileSerializer_bada.cpp
*  
*
*  Created by Alexander Trutchenko on 11/02/12.
*  Copyright 2012 Free Team. All rights reserved.
*
*/

#include "lid_lib/src/file_managment/LLFileSerializer.h"

#include "lid_lib/src/file_managment/LLFileUtils.h"
#include "lid_lib/src/service/LLAssert.h"

#include <stdio.h>

namespace lidlib {

////////////////////////////////////////////////////////
//
/** LLFileSerializer_bada
*  
*/
////////////////////////////////////////////////////////

class LLFileDescriptor_bada: public LLFileDescriptor
{
protected:
	FILE* _pFile;

public:
	LLFileDescriptor_bada(const std::string& fullFilePath, llFileDescriptorMode fdm)
	: LLFileDescriptor(fullFilePath, fdm)
	, _pFile(NULL)
	{
		switch(_fdm)
		{
		case kLLFileDescriptorMode_read: 
			{
				_pFile = fopen(fullFilePath.c_str(), "rb"); 
				if (_pFile == NULL)
					return;

				//Get size
				fseek(_pFile,0,SEEK_END);
				_size = ftell(_pFile);

				//Rewind on the begining
				rewind (_pFile);

				break;
			}
		case kLLFileDescriptorMode_rewrite:
			{
				_pFile = fopen(fullFilePath.c_str(), "wb"); 
				if (_pFile == NULL)
					return;

				break;
			}
		case kLLFileDescriptorMode_add: 
			{
				_pFile = fopen(fullFilePath.c_str(), "ab"); 
				if (_pFile == NULL)
					return;

				//Get size
				_size = ftell(_pFile);
				
				break;
			}
		};
	};

	virtual ~LLFileDescriptor_bada()
	{
		if (_pFile != NULL)
		{
			if (_fdm == kLLFileDescriptorMode_add || _fdm == kLLFileDescriptorMode_rewrite)
				fflush (_pFile);

			fclose(_pFile);
		}
	};

public:
	// Virtual interface
	bool isValid() const 
	{ 
		return _pFile != NULL; 
	} 
	bool readBlock(void* data, unsigned long size)
	{
		unsigned long retVal = fread(data, 1, size, _pFile);
		return (retVal == size);
	};
	bool writeBlock(const void* data, unsigned long size)
	{
		unsigned long retVal = fwrite(data, 1, size, _pFile);
		return (retVal == size);
	};
};

////////////////////////////////////////////////////////
//
/** LLFileSerializer
*  
*/
////////////////////////////////////////////////////////
// Private interface
	
LLFileDescriptor* LLFileSerializer::createDescriptorPlatform(const std::string& fullFilePath, llFileDescriptorMode dm)
{
	return new LLFileDescriptor_bada(fullFilePath, dm);
}

} // namespace lidlib
